<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User_auth {

	public function __construct()
	{
		$this->ci =& get_instance();
	}

	private function get()
	{
		$user = $this->ci->session->userdata('user');

		if ($user) {
			$passwd = $this->ci->session->userdata('passwd');
		} else {
			$user = $this->ci->input->post('user');
			$passwd = $this->ci->input->post('passwd');
		}

		return array('user' => $user, 'passwd' => $passwd);
	}

	public function check()
	{
		$data = $this->get();
		return !(empty($data['user']) && empty($data['passwd']));
	}

	public function validate()
	{
		$data = $this->get();
		$this->ci->load->model('user_model');

		$logok = $this->ci->user_model->get(array('name' => $data['user'],'passwd' => $data['passwd']))->num_rows()>0;

		if($logok)
		{
			$this->ci->session->set_userdata($data);
		}

		return $logok;
	}

	public function manage()
	{
		$check_auth = $this->check();

		if(!$check_auth){
			//REQUEST LOGIN
			redirect('module=users&submodule=login');
		}
		else
		{
			$logok = $this->validate();
			if(!$logok)
			{
				redirect('module=users&submodule=login_error');
			}
		}
	}
}


